package com.example.educationcommunity.controller;

import com.example.educationcommunity.mapper.CommentMapper;
import com.example.educationcommunity.mapper.QuestionMapper;
import com.example.educationcommunity.mapper.UserMapper;
import com.example.educationcommunity.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Controller
public class DeleteController {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable(name = "id") String id,
                         Model model){

        QuestionExample questionExample = new QuestionExample();
        questionExample.createCriteria()
                .andIdEqualTo(Integer.parseInt(id));
        Question question = questionMapper.selectByPrimaryKey(Integer.parseInt(id));
        User user = userMapper.selectByPrimaryKey(question.getCreator());
        user.setQuestionCount(user.getQuestionCount()-1);
        user.setActive(user.getActive()-5);
        userMapper.updateByPrimaryKey(user);
        questionMapper.deleteByExample(questionExample);

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria()
                .andParentIdEqualTo(Integer.parseInt(id));
        int count = (int) commentMapper.countByExample(commentExample);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        for(Comment comment:comments)
        {
            user = userMapper.selectByPrimaryKey(comment.getCommentator());
            user.setActive(user.getActive()-3);
            user.setCommentCount(user.getCommentCount()-1);
            userMapper.updateByPrimaryKey(user);
        }
        commentMapper.deleteByExample(commentExample);
        return "delete";
    }
}
